package com.ok.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ok.api.client.IntegralClient;
import com.ok.api.client.fallback.IntegralFallback;
import com.ok.common.exception.CustomException;
import com.ok.common.utils.JwtUtils;
import com.ok.user.domain.dto.OkUserDTO;
import com.ok.user.domain.po.OkUser;
import com.ok.user.mapper.OkUserMapper;
import com.ok.user.service.IOkUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2024-05-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OkUserServiceImpl extends ServiceImpl<OkUserMapper, OkUser> implements IOkUserService {

    private final IntegralClient integralClient;

    @Override
    public String login(OkUser user) {

        LambdaQueryWrapper<OkUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OkUser::getUsername, user.getUsername());

        OkUser one = this.getOne(queryWrapper);
        if (one == null){
            throw new CustomException("该用户未注册");
        }

        if (!one.getPassword().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))){
            throw new CustomException("密码错误");
        }

        HashMap<String, Object> map = new HashMap<>();

        map.put("userId", one.getId());
        map.put("username", one.getUsername());
        map.put("password", one.getPassword());

        return JwtUtils.generateJwt(map);
    }

    @Override
    @GlobalTransactional
    public void register(OkUserDTO userDTO) {
        OkUser okUser = new OkUser();
        BeanUtils.copyProperties(userDTO,okUser);
        //密码加密
        okUser.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        //添加用户信息
        this.save(okUser);

        LambdaQueryWrapper<OkUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OkUser::getUsername, userDTO.getUsername());
        OkUser user = this.getOne(queryWrapper);
        log.info("注册用户信息user：{}-id:{}",user,user.getId());
        //添加用户对应积分
        integralClient.add(user.getId());

    }

    @Override
    public void updateUser(OkUser user) {
        //密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        this.updateById(user);
    }


}
